package cn.edu.zafu.bigdata.x.huangxihao202211080211.UDP1;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockServer11 {
    public static void main(String[] args) {
        // 设置服务端端口号
        int port = 12345;

        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("时钟同步服务器启动，等待客户端请求...");

            while (true) {
                // 创建接收数据的包
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端的请求
                socket.receive(receivePacket);
                String clientAddress = receivePacket.getAddress().toString();
                int clientPort = receivePacket.getPort();
                System.out.println("收到来自客户端的请求: " + clientAddress + ":" + clientPort);

                // 获取当前时间
                String currentTime = getCurrentTime();
                byte[] sendData = currentTime.getBytes();

                // 创建响应包并发送给客户端
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                socket.send(sendPacket);
                System.out.println("已发送当前时间给客户端: " + currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取当前时间，格式为 yyyy-MM-dd HH:mm:ss
    private static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}

